package com.dhms.vostok1.utils

import android.util.Log
import org.java_websocket.client.WebSocketClient
import org.java_websocket.drafts.Draft
import org.java_websocket.handshake.ServerHandshake
import java.net.URI
import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets

class MessageClient(serverUri: URI?, draft: Draft?) :
    WebSocketClient(serverUri, draft, null, 2 * 1000) {

    private var listener: Listener? = null

    fun setListener(listener: Listener) {
        this.listener = listener
    }

    override fun onOpen(handshakedata: ServerHandshake) {
        Log.i(TAG, "opened connection")
        listener?.onOpen()
    }

    override fun onMessage(message: String) {
        Log.i(TAG, "onMessage_String: $message")
        listener?.onMessage(message)
    }

    override fun onMessage(bytes: ByteBuffer?) {
        super.onMessage(bytes)
        bytes?.let {
            val message = StandardCharsets.UTF_8.decode(it).toString()
            Log.i(TAG, "onMessage_bytes: $message")
            listener?.onMessage(message)
        }
    }

    override fun onClose(code: Int, reason: String, remote: Boolean) {
        Log.d(
            OFFLINE_DEBUG_TAG,
            "Connection closed by " + (if (remote) "remote peer" else "us") + " Code: " + code + " Reason: "
                    + reason
        )
        listener?.onClose(code, reason)
    }

    override fun onError(ex: java.lang.Exception) {
        Log.e(TAG, "onError:$ex")
        listener?.onError(ex)
    }

    companion object {
        private const val TAG = "MessageClient"
        const val OFFLINE_DEBUG_TAG = "OfflineTag"
    }

    interface Listener {
        fun onOpen() {}
        fun onMessage(message: String)
        fun onClose(code: Int, reason: String) {}
        fun onError(ex: java.lang.Exception) {}
    }

}
